﻿using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Globalization;

namespace GlennQuigmire.API.Application.Commands
{
    public class ExcelLeadOutHander : IRequestHandler<ExcelLeadOutCommand, Result>
    {

        private readonly IBaseRepositorys<InboundOrder> baseRepositorys;

        public ExcelLeadOutHander(IBaseRepositorys<InboundOrder> baseRepositorys)
        {
            this.baseRepositorys = baseRepositorys;
        }




        /// <summary>
        /// 导入入库单
        /// </summary>
        /// <param name="request">要导入的excel文件</param>
        /// <param name="cancellationToken">允许取消的Token</param>
        /// <returns>返回导入结果提示</returns>
        public async Task<Result> Handle(ExcelLeadOutCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            //获取文件扩展名 判断上传的文件类型是否正确
            var ext = Path.GetExtension(request.file.FileName);
            if (ext!= ".xlsx" && ext!= ".xls")
            {
                result.Messege = "请上传正确的Excel文件";
                return result;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                request.file.CopyTo(ms);
                ms.Position = 0;
                //根据文件扩展名创建对应的工作簿对象
                //获取工作簿
                IWorkbook wb = null;
                if (ext == ".xls")
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb=new XSSFWorkbook(ms);
                }
                //获取sheet 获取工作簿的第一个工作表
                ISheet sheet = wb.GetSheetAt(0);
                //获取总行数
                int totalRows = sheet.LastRowNum;
                //获取总列数
                int totalColumns = sheet.GetRow(0).LastCellNum;
                //创建一个用于存储解析后的数据列表
                var leadOutList = new List<InboundOrder>();
                //循环总行数 开头必须是1 不然从表头开始
                //遍历工作表的每一行（从第二行开始 因为第一行是表头）
                for (int i = 1; i <= totalRows; i++)
                {
                    //获取当前行
                    IRow row = sheet.GetRow(i);
                    //创建一个用于储存每一行解析后的数据对象
                    var dto = new InboundOrder();
                    //下标从0开始 导入时 外键需进行判断 客户不知道你的外键 只会输入文字
                    //日期转换
                    //日期在excel 表中必须是年月日格式，但不能加时分秒（注意！！！）
                    dto.InboundOrderNumber = row.GetCell(0).ToString();//入库单号
                    string InboundOrderDate = row.GetCell(1).ToString();//入库日期
                    /*dto.InboundOrderTypeId = int.Parse(row.GetCell(3).ToString());*/
                    //入库单类型判断
                    if (row.GetCell(2).ToString() == "普通入库")
                    {
                        dto.InboundOrderTypeId = 1;
                    }
                    else if (row.GetCell(2).ToString() == "采购入库")
                    {
                        dto.InboundOrderTypeId = 2;
                    }
                    else if (row.GetCell(2).ToString() == "成品入库")
                    {
                        dto.InboundOrderTypeId = 3;
                    }
                    else if (row.GetCell(2).ToString() == "调拨入库")
                    {
                        dto.InboundOrderTypeId = 4;
                    }
                    else if (row.GetCell(2).ToString() == "销售退货入库")
                    {
                        dto.InboundOrderTypeId = 5;
                    } else if (row.GetCell(2).ToString() == "其它入库")
                    {
                        dto.InboundOrderTypeId = 6;
                    }
                   
                    string CreateDate=row.GetCell(3).ToString();//创建日期
                    dto.CreateName = row.GetCell(4).ToString();//创建人
                    string[] multipleForats2 = { "dd-M月-yyyy", "yyyy-M-dd" };
                    DateTime date2;
                    foreach (var format in multipleForats2)
                    {
                        if(DateTime.TryParseExact(CreateDate, new[]{ format}, CultureInfo.CurrentCulture, DateTimeStyles.None, out date2))
                        {
                            dto.CreateDate = Convert.ToDateTime(date2.ToString("yyyy-MM-dd"));
                            break;
                        }
                    }
                    foreach (var format in multipleForats2)
                    {
                        if (DateTime.TryParseExact(InboundOrderDate, new[] { format }, CultureInfo.CurrentCulture, DateTimeStyles.None, out date2))
                        {
                            dto.InboundOrderDate = Convert.ToDateTime(date2.ToString("yyyy-MM-dd"));
                            break;
                        }
                    }

                    dto.Remark = row.GetCell(5).ToString();//备注
                    //添加到集合中
                    leadOutList.Add(dto);
                }
                //跳出循环后 使用AddRange进行批量添加
                var res = await baseRepositorys.AddRange(leadOutList);
                if (res > 0)
                {
                    result.Messege = "导入成功";
                }
                else
                {
                    result.Messege = "导入失败";
                }
                return result;


            }

        }
    }
}
